/**
 * Leaflet的React灵活实现
 * 该方法是将Leaflet的写法使用Component进行包装
 */
import React from 'react';
import HereTileLayers from "../layers/hereTileLayers";
import L from "leaflet";
import './LeafletMapScene.css';

class LeafletMapScene extends React.Component {
    constructor() {
        super();
        this.state = {
            mapParams : {
                center: [20, 0],
                zoomControl: false,
                maxBounds: L.latLngBounds(L.latLng(-90, -180), L.latLng(90, 180)),
                zoom: 2
            }
        }
    }

    componentDidMount() {
        // 地图图层
        var heremap = HereTileLayers.here({
            appId: "jKco7gLGf0WWlvS5n2fl",
            appCode: "HQnCztY23zh2xiTPCFiTMA",
            scheme: "reduced.day"
        });
        var osmmap = L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
            id: 'paulserraino.n0dn3pbe',
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> contributors'
        });
        // 设置地图
        this.map = L.map("map", this.state.mapParams);
        // 将osmmap作为默认图层
        osmmap.addTo(this.map);
        // our basemap and add it to the map
        const baseMaps = {
            "HERE reduced.day": heremap,
            "MapBOX": osmmap,
        };
        L.control.layers(baseMaps).addTo(this.map);
    
        // 添加一个zoom控件
        L.control.zoom({ position: "topright" }).addTo(this.map);

        // 获取geojson数据
        fetch("/api/cities")
            .then(response => response.json())
            .then(data => {
                data.features.forEach(feature => {
                    const coord = feature.geometry.coordinates;
                    L.marker([coord[1], coord[0]]).addTo(this.map)
                        .bindPopup(feature.properties.name);
                });
            });
    }
    
    render() {
        return <div id="map"/>;
    }
}
export default LeafletMapScene;